package com.ow.dva.util.lockSocket;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author yanzengbao
 * @Description: Socket 启动相关工具类
 * @Date:2017/11/2 9:30
 */
@SpringBootApplication
public class MySocketUtil {

    public static Map<String, SocketTask> socketTaskMap = Collections.synchronizedMap(new HashMap<>());

    //创建线程池
    private static ExecutorService threadPool = Executors.newCachedThreadPool();
    //Socket监听服务
    private static ServerSocket server;
    //Socket监听端口
    private static Integer port = 12315;

    /**
     * 启动服务
     * @throws IOException 异常
     */
    public  void start() throws IOException {
        //定义一个ServerSocket监听在指定端口上
        server = new ServerSocket(port);
        System.out.println("创建socket:"+port);
        beginAccept();
    }


    /**
     * @Author yanzengbao
     * @Description: 阻塞连接，开始监控
     * @Date:2017/11/2 11:11
     */
    public static void beginAccept() throws IOException{
        while (true) {
            //调用accept()方法开始监听，等待客户端的连接
            Socket socket = server.accept();
            System.out.println("监听socket："+socket);
            //每接收到一个Socket就建立一个新的线程来处理它。并添加到线程池中。
            SocketTask socketTask = new SocketTask(socket);
            threadPool.execute(new Thread(socketTask));
        }

    }



    /**
     * @Author yanzengbao
     * @Description: 关闭监听
     * @Date:2017/11/2 11:15
     */
    public static void closeServerSocket() throws IOException {
        System.out.println(server.isClosed());
        //关闭监听
        server.close();
    }

}

